//
//  ImagesAndContentTableViewCell.m
//  YellowBridge
//
//  Created by 王右 on 2018/12/3.
//  Copyright © 2018 王右. All rights reserved.
//

#import "ImagesAndContentTableViewCell.h"
#import "ImageCollectionViewCell.h"

@interface ImagesAndContentTableViewCell ()<QMUITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,XLPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) UICollectionView *imagesCollectionView;

@property (strong, nonatomic)  QMUITextView *contentTextView;

@property (nonatomic, assign) CGFloat cellHeight;
@end


@implementation ImagesAndContentTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.imageArr = [NSMutableArray array];
    _cellHeight = 180;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置CollectionView的属性
    self.imagesCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12, 17 + _nameLabel.bounds.size.height, SCREEN_WIDTH - 12, 80) collectionViewLayout:flowLayout];
    self.imagesCollectionView.backgroundColor = [UIColor whiteColor];
    self.imagesCollectionView.delegate = self;
    self.imagesCollectionView.dataSource = self;
    self.imagesCollectionView.scrollEnabled = YES;
    [self addSubview:self.imagesCollectionView];
    //注册Cell
    [self.imagesCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ImageCollectionViewCell class]) bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ImageCollectionViewCell"];
    self.imagesCollectionView.showsHorizontalScrollIndicator = NO;
    
    _contentTextView = [[QMUITextView alloc] init];
    [self addSubview:_contentTextView];
    
    [_contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_nameLabel);
        make.bottom.right.equalTo(self).with.offset(-15);
        make.top.equalTo(self->_imagesCollectionView.mas_bottom).with.offset(5);
    }];
    _contentTextView.delegate = self;
    _contentTextView.placeholder = @"请输入文字说明";
    _contentTextView.font = [UIFont systemFontOfSize:15];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return !_canEdit ? _imageArr.count : (_imageArr.count+1>9?9:_imageArr.count+1);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
    [cell.deleteButton setActionWithBlock:^(UIControl *control) {
        [self->_imageArr removeObjectAtIndex:indexPath.row];
        [self->_imagesCollectionView reloadData];
    }];
    if (_canEdit) {
        cell.type = ImageCellTypeCanDelete;
    }else{
        cell.type = ImageCellTypeNormal;
    }
    if (indexPath.row == _imageArr.count) {
        cell.imageView.image = [UIImage imageNamed:@"加图片"];
        cell.type = ImageCellTypeNormal;
    }else{
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_imageArr[indexPath.row]]];
    }
    return cell;
}

- (void)setImageArr:(NSMutableArray *)imageArr{
    if (imageArr.count) {
        _imageArr = imageArr;
        [_imagesCollectionView reloadData];
    }else{
        _imageArr = [NSMutableArray array];
    }
}

#pragma mark  定义每个UICollectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return  CGSizeMake(80,80);
}

#pragma mark  点击CollectionView触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_canEdit) {
        if (indexPath.item == _imageArr.count) {
            __weak typeof(self) weakSelf = self;
            LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                if (index == 0) {
                    [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                }else  if (index == 1){
                    [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                }
            }];
            [sheet show];
        }
    }else{
            XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:_imageArr currentImageIndex:indexPath.row];
            browser.pageControlStyle = XLPhotoBrowserPageControlStyleClassic;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    _textViewText = textView.text;
    self.isContentReload = YES;
    [_superTableView reloadRowsAtIndexPaths:@[[_superTableView indexPathForCell:self]] withRowAnimation:(UITableViewRowAnimationNone)];
}

- (void)textView:(QMUITextView *)textView newHeightAfterTextChanged:(CGFloat)height{
    CGFloat newHeight = height + 147;
    _cellHeight = newHeight;
    _textViewText = textView.text;
}

- (CGFloat )returnCellHeight{
    if (_canEdit) {
        return _cellHeight;
    }else{
        return _cellHeight + [self returnContentTextHeightWithText:_textViewText withFont:_contentTextView.font];
    }
}

- (CGFloat )returnContentTextHeightWithText:(NSString *)content withFont:(UIFont *)font{
    QMUITextView *label = [[QMUITextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-25, NSIntegerMax)];
    label.text = content;
    label.font = font;
    [label sizeToFit];
    CGSize size = label.bounds.size;
    return size.height-30;
}

- (void)setCanEdit:(BOOL)canEdit{
    if (canEdit) {
        _contentTextView.userInteractionEnabled = YES;
    }else{
        _contentTextView.userInteractionEnabled = NO;
    }
    _canEdit = canEdit;
}

- (void)setTextViewText:(NSString *)textViewText{
    if (textViewText.length != 0) {
        _textViewText = textViewText;
        _contentTextView.text = textViewText;
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

#pragma mark 编辑照片
-(void)editViewWithImage:(UIImage *)image{
    [[self topViewController] hudWithText:@"图片上传中..."];
    [RequestManager uploadImageWithImage:image success:^(NSDictionary *obj) {
        [[self topViewController] removeHud];
        [[self topViewController].view makeToast:@"上传图片成功!"];
        NSDictionary *imageDic = obj[@"result"];
        NSString *imageUrl = imageDic[@"fileurl"];
        [self->_imageArr addObject:imageUrl];
        [self->_imagesCollectionView reloadData];
    } failure:^(NSString *error) {
        [[self topViewController] removeHud];
        [[self topViewController].view makeToast:@"上传图片失败,请重新选择上传!"];
    }];
}

#pragma mark UIImagePickerController - delegate
-(void)showImagePickerWithType:(UIImagePickerControllerSourceType )type{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = type;
    imagePickerController.delegate = self;
    [[self topViewController] presentViewController:imagePickerController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self editViewWithImage:image];
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end
